package com.azt.provider.impl;

import com.azt.api.pojo.CompanyBusiness;
import com.azt.api.service.CompanyService;
import com.azt.provider.mapper.CompanyBusinessMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.azt.api.pojo.Company;
import com.azt.api.pojo.CompanyApplifield;
import com.azt.api.pojo.CompanyCategory;
import com.azt.api.service.CompanyApplifieldService;
import com.azt.provider.mapper.CompanyApplifieldMapper;
import com.azt.provider.mapper.CompanyCategoryMapper;

import tk.mybatis.mapper.entity.Example;


@Transactional
@Service
public class CompanyApplifieldServiceImpl implements CompanyApplifieldService {


	@Autowired
	private CompanyCategoryMapper companyCategoryMapper;

	@Autowired
	private CompanyApplifieldMapper companyApplifieldMapper;

	@Autowired
	private CompanyBusinessMapper companyBusinessMapper;

	@Autowired
	private CompanyService companyService;

	@Override
	public void saveOrUpdateFields(Company company) {
		if(company.getId() != null){
			if(CollectionUtils.isNotEmpty(company.getCompanyCategorys())) {
				Example exp = new Example(CompanyCategory.class);
				exp.createCriteria().andEqualTo("companyId", company.getId());
				companyCategoryMapper.deleteByExample(exp);
				//companyCategoryMapper.insertList(company.getCompanyCategorys());
				for (CompanyCategory companyCategory : company.getCompanyCategorys()) {
					companyCategoryMapper.insert(companyCategory);
				}
			}
			if(CollectionUtils.isNotEmpty(company.getCompanyApplifields())) {
				Example exp = new Example(CompanyApplifield.class);
				exp.createCriteria().andEqualTo("companyId", company.getId());
				companyApplifieldMapper.deleteByExample(exp);
				for (CompanyApplifield companyApplifield : company.getCompanyApplifields()) {
					companyApplifieldMapper.insert(companyApplifield);
				}
				//companyApplifieldMapper.insertList(company.getCompanyApplifields());
			}
			if(CollectionUtils.isNotEmpty(company.getCompanyBusinesses())) {
				Example exp = new Example(CompanyBusiness.class);
				exp.createCriteria().andEqualTo("companyId", company.getId());
				companyBusinessMapper.deleteByExample(exp);
				for (CompanyBusiness companyBusiness : company.getCompanyBusinesses()) {
					companyBusinessMapper.insert(companyBusiness);
				}
			}

			/**
			 * 修改经营领域也需要审核
			 */
			Company old = companyService.getCompanyById(company.getId());
			old.setAuditState(Company.AUDIT_STATE_EDIT);
			companyService.saveOrUpdateCompany(old, null, true);
		}
	}
	
	
}
